var merida = new google.maps.LatLng(20.96700006273209, -89.62382276275639);
var marker;
var map;
var lat;
var lon;

function initialize() {
    lat = document.getElementById('latitude');
    lon = document.getElementById('longitude');
    
    var mapOptions = {
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: merida
    };

    map = new google.maps.Map(document.getElementById("map"),
            mapOptions);
    
    if(lat.value != '' && lon.value != ''){
        merida = new google.maps.LatLng(lat.value,lon.value);
        createMarker(merida);
    }
    
    google.maps.event.addListener(map, 'click', function(event){
            ubicarCentroComercial(event.latLng);
        }
    );
    
    
}

function createMarker(ubicacion){
     marker = new google.maps.Marker({
            map:map,
            draggable:true,
            animation: google.maps.Animation.DROP,
            position: ubicacion
        });
    google.maps.event.addListener(marker, 'click', toggleBounce);
    google.maps.event.addListener(marker, 'dragend', function(event){
        changePosition(event.latLng);
    });
}

function ubicarCentroComercial(ubicacion){
    if (marker == null){
        createMarker(ubicacion);
        changePosition(ubicacion);
    }else{
        marker.setPosition(ubicacion);
        changePosition(ubicacion);
    }
}

function changePosition(position){
    lat.value = position.lat();
    lon.value = position.lng();
}

function toggleBounce() {
    if (marker.getAnimation() != null) {
        marker.setAnimation(null);
    } else {
        marker.setAnimation(google.maps.Animation.BOUNCE);
    }
}



window.onload = initialize;